package com.xjy.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.xjy.common.core.domain.AjaxResult;
import com.xjy.common.core.domain.entity.SysUser;
import com.xjy.common.exception.CustomException;
import com.xjy.common.exception.UtilException;
import com.xjy.common.utils.PageUtils;
import com.xjy.common.core.page.PagePlus;
import com.xjy.common.core.page.TableDataInfo;
import com.xjy.system.domain.SysCreditAdvance;
import com.xjy.system.domain.SysPayaccount;
import com.xjy.system.domain.bo.*;
import com.xjy.system.domain.vo.SysCreditAdvanceVo;
import com.xjy.system.service.ISysCheckaccountService;
import com.xjy.system.service.ISysFundaccountdetailService;
import com.xjy.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xjy.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjy.system.domain.SysColpaydec;
import com.xjy.system.mapper.SysColpaydecMapper;
import com.xjy.system.domain.vo.SysColpaydecVo;
import com.xjy.system.service.ISysColpaydecService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 收入记账信息Service业务层处理
 *
 * @author xjy
 * @date 2022-02-14
 */
@Service
public class SysColpaydecServiceImpl extends ServicePlusImpl<SysColpaydecMapper, SysColpaydec> implements ISysColpaydecService {
	@Autowired
	private ISysFundaccountdetailService iSysFundaccountdetailService;
	@Autowired
	private ISysCheckaccountService iSysCheckaccountService;

	@Autowired
	private ISysUserService iSysUserService;

    @Override
    public SysColpaydecVo queryById(Long id){
        return getVoById(id, SysColpaydecVo.class);
    }

    @Override
    public TableDataInfo<SysColpaydecVo> queryPageList(SysColpaydecQueryBo bo) {
        PagePlus<SysColpaydec, SysColpaydecVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), SysColpaydecVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<SysColpaydecVo> queryList(SysColpaydecQueryBo bo) {
        return listVo(buildQueryWrapper(bo), SysColpaydecVo.class);
    }

    private LambdaQueryWrapper<SysColpaydec> buildQueryWrapper(SysColpaydecQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysColpaydec> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getContractName()), SysColpaydec::getContractName, bo.getContractName());
		lqw.eq(bo.getProjId() != null, SysColpaydec::getProjId, bo.getProjId());
        lqw.eq(StrUtil.isNotBlank(bo.getColpayNo()), SysColpaydec::getColpayNo, bo.getColpayNo());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getColpayType()), SysColpaydec::getColpayType, bo.getColpayType());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getColpayWay()), SysColpaydec::getColpayWay, bo.getColpayWay());
		lqw.in(null != bo.getIdList() && bo.getIdList().size() > 0, SysColpaydec::getId,bo.getIdList());

		return lqw;
    }

    @Override
    public Boolean insertByAddBo(SysColpaydecAddBo bo) {
        SysColpaydec add = BeanUtil.toBean(bo, SysColpaydec.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(SysColpaydecEditBo bo) {
        SysColpaydec update = BeanUtil.toBean(bo, SysColpaydec.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

	@Override
	@Transactional
	public synchronized Boolean auditByEditBo(BaseAuditBo req) {
		boolean rsp = false;
		List<Long> idList = req.getIdList();
		if(null == idList || idList.size() == 0){
			throw new CustomException("需审核的数据不能为空！");
		}
		SysColpaydecQueryBo sysColpaydecQueryBo = new SysColpaydecQueryBo();
		sysColpaydecQueryBo.setIdList(idList);
		sysColpaydecQueryBo.setAuditStatus(false);
		List<SysColpaydecVo> sysColpaydecVoList = this.queryList(sysColpaydecQueryBo);
		for(SysColpaydecVo sysColpaydecVo:sysColpaydecVoList){
			// TODO 结账效验
			iSysCheckaccountService.check(sysColpaydecVo.getProjId(),sysColpaydecVo.getColpayTime());

			SysColpaydec update = new SysColpaydec();
			update.setId(sysColpaydecVo.getId());
			boolean changeFundaccount = this.changeFundaccount(sysColpaydecVo);
			if(!changeFundaccount){
				throw new CustomException("更新资金流水失败！");
			}
			update.setAuditStatus(true);
			rsp = baseMapper.updateById(update) > 0;
		}
		return rsp;

	}

	private synchronized Boolean changeFundaccount(SysColpaydecVo req){

		SysFundaccountdetailAddBo addBo = new SysFundaccountdetailAddBo();

		addBo.setCategory(0L);
		addBo.setProjId(req.getProjId());
		addBo.setProjName(req.getProjName());
		addBo.setSubjectId(req.getBudgetId());
		addBo.setSubjectName(req.getBudgetName());
		addBo.setContractId(req.getContractId());
		addBo.setContractName(req.getContractName());
		addBo.setSettleProj(req.getResultProjId());
		addBo.setSettleProjName(req.getResultProjName());

		addBo.setAccId(req.getColpayAccountId());
		addBo.setAccountName(req.getColpayAccountName());
		addBo.setAccountBank(req.getColpayAccountBank());
		addBo.setAccountNo(req.getColpayAccountNo());
		addBo.setTransactionId(req.getColpayNo());
		addBo.setTransactionCategory(7L);

		addBo.setSenderId(req.getColpaySource());
		addBo.setSender(req.getColpaySourceName());
		addBo.setReceiveId(req.getColpayAccountId());
		addBo.setReceive(req.getColpayAccountName());
		addBo.setManagerId(req.getHandlerId());
		addBo.setManager(req.getHandler());
		addBo.setTransactionType(req.getColpayWay());

		addBo.setTransactionDate(req.getColpayTime());
		addBo.setAmount(req.getColpayAmt());
		addBo.setRemarks(req.getColpayDec());
		return iSysFundaccountdetailService.insertByAddBo(addBo);
	}

	/**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysColpaydec entity){
        //TODO 做一些数据校验,如唯一约束
		// TODO 结账效验
		iSysCheckaccountService.check(entity.getProjId(),entity.getColpayTime());
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	@Override
	public AjaxResult<List<SysUser>> queryColpayName(String colpayName) {
		LambdaQueryWrapper<SysUser> lmd = Wrappers.lambdaQuery();
		lmd.select(SysUser::getUserName,SysUser::getUserId)
			.like(StrUtil.isNotBlank(colpayName), SysUser::getUserName, colpayName);
		return AjaxResult.success(iSysUserService.list(lmd));
	}

	@Override
	public AjaxResult<List<SysUser>> queryColpayHandler(String handler) {
		LambdaQueryWrapper<SysUser> lmd = Wrappers.lambdaQuery();
		lmd.select(SysUser::getUserName,SysUser::getUserId)
			.like(StrUtil.isNotBlank(handler), SysUser::getUserName, handler);
		return AjaxResult.success(iSysUserService.list(lmd));
	}
}
